package com.agh.portal.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.agh.portal.data.DataComponent;
import com.agh.portal.domain.Ad;
import com.agh.portal.domain.Answer;
import com.agh.portal.domain.Comment;
import com.agh.portal.domain.CourseStudent;
import com.agh.portal.domain.MainPagePost;
import com.agh.portal.domain.Post;
import com.agh.portal.domain.Question;
import com.agh.portal.domain.Reply;
import com.agh.portal.domain.Student;
import com.agh.portal.domain.enumeration.Gender;
import com.agh.portal.domain.enumeration.StudentStatus;
import com.agh.portal.domain.security.User;
import com.agh.portal.service.DataService;
import com.agh.portal.service.StudentService;

@RequestMapping("/students")
@Controller
@RooWebScaffold(path = "students", formBackingObject = Student.class)
@RooWebFinder
public class StudentController {
	
	@Autowired
	StudentService studentService;
	
	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid @ModelAttribute(value="student") Student student, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, student);
            return "students/create";
        }
        uiModel.asMap().clear();
        student.persist();
        return "redirect:/students/" + encodeUrlPathSegment(student.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Student());
        return "students/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
		Student student = Student.findStudent(id);
		if(student==null){
			return "redirect:/";
		}
		
		List<Ad> ads = Ad.findLatestAdsByStudent(student, 4).getResultList();
		List<Question> questions = Question.findLatestQuestionsByStudent(student, 4).getResultList();
		List<MainPagePost> mainPagePosts = MainPagePost.findLatestMainPagePostsByStudent(student, 4).getResultList();
		
		List<DataComponent> latestActivities = new ArrayList<DataComponent>();
		latestActivities.addAll(DataService.parseAdsToDataComponent(ads));
		latestActivities.addAll(DataService.parseMainPagePostsToDataComponent(mainPagePosts));
		latestActivities.addAll(DataService.parseAnswersToDataComponent(Answer.findLatestAnswersByStudent(student, 4).getResultList()));
		latestActivities.addAll(DataService.parseCommentsToDataComponent(Comment.findLatestCommentsByStudent(student, 4).getResultList()));
		latestActivities.addAll(DataService.parsePostsToDataComponent(Post.findLatestPostsByStudent(student, 4).getResultList()));
		latestActivities.addAll(DataService.parseRepliesToDataComponent(Reply.findLatestReplysByStudent(student, 4).getResultList()));
		latestActivities.addAll(DataService.parseQuestionsToDataComponent(questions));
	
		DataService.sortByDateDesc(latestActivities);
			
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("latestActivities", latestActivities);
        uiModel.addAttribute("aghGroups", student.getAghGroups());
        uiModel.addAttribute("courses", studentService.getCoursesByStudent(student));
        uiModel.addAttribute("ads", ads);
        uiModel.addAttribute("mainPagePosts",  mainPagePosts);
        uiModel.addAttribute("questions", questions);
        uiModel.addAttribute("student", Student.findStudent(id));
        uiModel.addAttribute("itemId", id);
        return "students/show";
    }

	@Secured("ROLE_ADMIN")
	@RequestMapping(produces = "text/html")
    public String list(
    		@RequestParam(value = "page", required = false) Integer page, 
    		@RequestParam(value = "size", required = false) Integer size, 
    		Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            List<Student> students = Student.findStudentEntries(firstResult, sizeNo);
        	for(Student s : students){
    			s.setLocked(User.findUsersByEmailAddress(s.getEmail()).getSingleResult().getLocked());
        	}
            uiModel.addAttribute("students", students);
            float nrOfPages = (float) Student.countStudents() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
        	List<Student> students = Student.findAllStudents();
        	for(Student s : students){
    			s.setLocked(User.findUsersByEmailAddress(s.getEmail()).getSingleResult().getLocked());
        	}
            uiModel.addAttribute("students", students);
        }
        addDateTimeFormatPatterns(uiModel);
        return "students/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Student student, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
        	System.out.println(bindingResult.getAllErrors());
            populateEditForm(uiModel, student);
            return "students/update";
        }
        uiModel.asMap().clear();
        student.merge();
        return "redirect:/dashboard";
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, Student.findStudent(id));
        return "students/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Student student = Student.findStudent(id);
        student.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/students";
    }

	void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("student_dateofbirth_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

	void populateEditForm(Model uiModel, Student student) {
        uiModel.addAttribute("student", student);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("ads", Ad.findAllAds());
        uiModel.addAttribute("answers", Answer.findAllAnswers());
        uiModel.addAttribute("coursestudents", CourseStudent.findAllCourseStudents());
        uiModel.addAttribute("mainpageposts", MainPagePost.findAllMainPagePosts());
        uiModel.addAttribute("questions", Question.findAllQuestions());
        uiModel.addAttribute("genders", Arrays.asList(Gender.values()));
        uiModel.addAttribute("studentstatuses", Arrays.asList(StudentStatus.values()));
        
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }

	@RequestMapping(params = { "find=ByCityOfOrigin", "form" }, method = RequestMethod.GET)
    public String findStudentsByCityOfOriginForm(Model uiModel) {
        return "students/findStudentsByCityOfOrigin";
    }

	@RequestMapping(params = "find=ByCityOfOrigin", method = RequestMethod.GET)
    public String findStudentsByCityOfOrigin(@RequestParam("cityOfOrigin") String cityOfOrigin, Model uiModel) {
        uiModel.addAttribute("students", Student.findStudentsByCityOfOrigin(cityOfOrigin).getResultList());
        return "students/list";
    }

	@RequestMapping(params = { "find=ByNameAndSurnameLike", "form" }, method = RequestMethod.GET)
    public String findStudentsByNameAndSurnameLikeForm(Model uiModel) {
        return "students/findStudentsByNameAndSurnameLike";
    }

	@RequestMapping(params = "find=ByNameAndSurnameLike", method = RequestMethod.GET)
    public String findStudentsByNameAndSurnameLike(@RequestParam("name") String name, @RequestParam("surname") String surname, Model uiModel) {
        uiModel.addAttribute("students", Student.findStudentsByNameAndSurnameLike(name, surname).getResultList());
        return "students/list";
    }
	
	
}
